package com.lktx.sso.config;

import cn.dev33.satoken.oauth2.data.loader.SaOAuth2DataLoader;
import cn.dev33.satoken.oauth2.data.model.loader.SaClientModel;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hutool.core.util.StrUtil;
import com.lktx.sso.admin.entity.SsoApp;
import com.lktx.sso.admin.entity.SsoAppOidcConfig;
import com.lktx.sso.admin.mapper.SsoAppMapper;
import com.lktx.sso.admin.mapper.SsoAppOidcConfigMapper;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Bean
public class SaOAuth2DataLoaderImpl implements SaOAuth2DataLoader {

    @Autowired
    private SsoAppMapper ssoAppMapper;

    @Autowired
    private SsoAppOidcConfigMapper ssoAppOidcConfigMapper;

    // 根据 clientId 获取 Client 信息
    @Override
    public SaClientModel getClientModel(String clientId) {
        SsoApp ssoApp = ssoAppMapper.selectOneByQuery(QueryWrapper.create().eq(SsoApp::getClientId, clientId));
        if (ssoApp == null||(ssoApp.getStatus()!=null&&ssoApp.getStatus()==1)) {
            return null;
        }
        SsoAppOidcConfig ssoAppOidcConfig = ssoAppOidcConfigMapper.selectOneById(ssoApp.getSsoAppId());
        if (ssoAppOidcConfig == null) {
            return null;
        }

        List<String> redirectUris = new ArrayList<>();
        if (StrUtil.isNotEmpty(ssoAppOidcConfig.getRedirectUris())) {
            redirectUris.add(ssoAppOidcConfig.getRedirectUris());
        }
        if (StrUtil.isNotEmpty(ssoAppOidcConfig.getPostLogoutRedirectUris())) {
            redirectUris.add(ssoAppOidcConfig.getRedirectUris());
        }
        if (redirectUris.isEmpty()) {
            redirectUris.add("*");
        }

        Set<String> authGrantTypes = ssoAppOidcConfig.getAuthGrantTypes();

        return new SaClientModel()
                .setClientId(ssoApp.getClientId())    // client id
                .setClientSecret(ssoApp.getClientSecret())    // client 秘钥
                .addAllowRedirectUris(redirectUris.toArray(new String[0]))    // 所有允许授权的 url
                .addContractScopes(ssoAppOidcConfig.getGrantScopes().toArray(new String[0]))    // 所有签约的权限
                .addAllowGrantTypes(authGrantTypes.toArray(new String[0]));
    }

    // 根据 clientId 和 loginId 获取 openid
    @Override
    public String getOpenid(String clientId, Object loginId) {
        return SaOAuth2DataLoader.super.getOpenid(clientId, loginId);
    }

}